﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using DIWAGIS;
using DIWAGIS.ApplicationLayer.BoCongCuQuanLy;


namespace DIWAGIS.ApplicationLayer.XemThongTin
{
    public partial class frmCapNhatThongTinDoiTuong : System.Windows.Forms.Form
    {
        private IMapControl4 m_mapControl;
        public IMapControl4 mapControl
        {
            get { return m_mapControl; }
            set { m_mapControl = value; }
        }
        private ILayer m_targetLayer;
        public ILayer targetLayer
        {
            set { m_targetLayer = value; }
            get { return m_targetLayer; }
        }

        private IFeature m_selectedFeature;
        public IFeature selectedFeature
        {
            set
            {
                m_selectedFeature = value;
                LoadData();
            }
            get { return m_selectedFeature; }
        }
        Class.Editing editing;
        private IWorkspace m_workspace;

        private IEngineEditor m_editor;
        public IEngineEditor editor
        {
            get { return m_editor; }
            set { m_editor = value; }
        }
        public frmCapNhatThongTinDoiTuong()
        {
            InitializeComponent();
        }

        private DataTable tblData;
        DataRow newRow;
        private void CreateTable()
        {
            DataColumn colSTT = new DataColumn("STT", typeof(string));
            DataColumn colTruongTTAlias = new DataColumn("colTruongTTAlias", typeof(string));
            DataColumn colTruongTT = new DataColumn("colTruongTT", typeof(string));
            DataColumn colGiaTri = new DataColumn("colGiaTri", typeof(object));
            DataColumn colEditable = new DataColumn("colEditable", typeof(bool));

            tblData = new DataTable();
            tblData.Columns.Add(colSTT);
            tblData.Columns.Add(colTruongTT);
            tblData.Columns.Add(colTruongTTAlias);
            tblData.Columns.Add(colGiaTri);
            tblData.Columns.Add(colEditable);
        }

        /// <summary>
        /// Kết nối tới CSDL
        /// </summary>
        private IWorkspace ConnectToSDE()
        {
            string strServerName = Class.ClassVariables.ThongTinDangNhap.strServerName;
            string strInstance = Class.ClassVariables.ThongTinDangNhap.strInstance;
            string strDatabaseName = Class.ClassVariables.ThongTinDangNhap.strDatabase;
            string strUser = Class.ClassVariables.ThongTinDangNhap.strUser;
            string strPassword = Class.ClassVariables.ThongTinDangNhap.strPassword;
            string strVersion = Class.ClassVariables.ThongTinDangNhap.strVersion;
            editing = new Class.Editing();
            m_workspace = editing.ConnectSDE(strServerName, strInstance, strDatabaseName, strUser, strPassword, strVersion);
            return m_workspace;
        }

        public void ClearData()
        {
            if (tblData != null)
            {
                tblData.Rows.Clear();
            }
        }
        private void btnCloseForm_Click(object sender, EventArgs e)
        {
            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                Class.clsStaticFunctions.ThongBaoLoi(ex);
            }
        }

        public void LoadData()
        {
            if (m_selectedFeature != null)
            {
                CreateTable();
                for (int i = 0; i < m_selectedFeature.Fields.FieldCount; i++)
                {
                    if (m_selectedFeature.Fields.get_Field(i).Type != esriFieldType.esriFieldTypeGeometry)
                    {
                        newRow = tblData.NewRow();
                        newRow[0] = (i+1).ToString();
                        newRow[1] = m_selectedFeature.Fields.get_Field(i).Name;
                        //MessageBox.Show(m_selectedFeature.Fields.get_Field(i).Name.ToString());
                        newRow[2] = m_selectedFeature.Fields.get_Field(i).AliasName;
                        newRow[3] = m_selectedFeature.get_Value(i);
                        if ((m_selectedFeature.Fields.get_Field(i).Editable == true))//.Type != esriFieldType.esriFieldTypeOID) && (m_selectedFeature.Fields.get_Field(i).Name.ToUpper() != "SHAPE_LENGTH") && (m_selectedFeature.Fields.get_Field(i).Name.ToUpper() != "SHAPE_AREA"))
                        {
                            newRow[4] = true;
                        }
                        else
                            newRow[4] = false;

                        tblData.Rows.Add(newRow);
                    }
                }
                gridControl.DataSource = tblData;
            }
        }
        
        #region Trình bày gridview

        //private void gridView_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        //{
        //    try
        //    {
        //        if (e.Column.Name == "colGiaTri")
        //        {
        //            if (gridView.GetRowCellValue(e.RowHandle, "colEditable") != null)
        //            {
        //                bool editable = bool.Parse(gridView.GetRowCellValue(e.RowHandle, "colEditable").ToString());
        //                if (editable == false)
        //                {
        //                    e.Appearance.BackColor = Color.LightGray;
        //                    DisableRow(e.RowHandle);
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Class.clsStaticFunctions.ThongBaoLoi(ex);
        //    }
        //}

        //private void gridView_ShowingEditor(object sender, CancelEventArgs e)
        //{
        //    e.Cancel = IsRowDisabled(gridView.GetDataSourceRowIndex(gridView.FocusedRowHandle));
        //}

        public bool IsRowDisabled(int dataSourceRowIndex)
        {
            return DisabledRows.Contains(dataSourceRowIndex);
        }

        public void DisableRow(int dataSourceRowIndex)
        {
            DisabledRows.Add(dataSourceRowIndex);
        }

        public void EnableRow(int dataSourceRowIndex)
        {
            while (IsRowDisabled(dataSourceRowIndex))
            {
                DisabledRows.Remove(dataSourceRowIndex);
            }
        }

        private List<int> _DisabledRows;

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<int> DisabledRows
        {
            get { return _DisabledRows; }
        }
        #endregion

        //private void gridView_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        //{
        //    try
        //    {
        //        Class.clsStaticFunctions.ShowIndicator(e);
        //    }
        //    catch (Exception ex)
        //    {
        //        Class.clsStaticFunctions.ThongBaoLoi(ex);
        //    }
        //}

        private void btnChonDoiTuong_Click(object sender, EventArgs e)
        {
            try
            {
                //m_editor=new EngineEditorClass();
                IEngineEditLayers layerEdit = m_editor as IEngineEditLayers;
                targetLayer = layerEdit.TargetLayer as ILayer;

                DIWAGIS.ApplicationLayer.BoCongCuQuanLy.ToolUpdateInfo toolUpdate = new DIWAGIS.ApplicationLayer.BoCongCuQuanLy.ToolUpdateInfo();
                toolUpdate.frmCapNhat = this;
                toolUpdate.targetLayer = targetLayer;
                toolUpdate.OnCreate(m_mapControl);
                toolUpdate.editor = m_editor;
                m_mapControl.CurrentTool = toolUpdate;
            }
            catch (Exception ex)
            {
                Class.clsStaticFunctions.ThongBaoLoi(ex);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                ConnectToSDE();
                editing.StartEditingAttribute_SDE(m_workspace);
                if (editor.EditState == esriEngineEditState.esriEngineStateEditing)
                {
                    for (int i = 0; i < tblData.Rows.Count; i++)
                    {
                        for (int j = 0; j < selectedFeature.Fields.FieldCount; j++)
                        {
                            if ((tblData.Rows[i]["colTruongTT"].ToString() == selectedFeature.Fields.get_Field(j).Name) && (bool.Parse(tblData.Rows[i]["colEditable"].ToString()) == true))
                            {
                                selectedFeature.set_Value(j, tblData.Rows[i]["colGiaTri"]);
                            }
                        }
                    }
                    selectedFeature.Store();
                    editing.StopEditingSDE_WithoutAlert(m_workspace);
                    //ICommand cmdSaveEdit = new ControlsEditingSaveCommandClass();
                    //cmdSaveEdit.OnCreate(mapControl);
                    //cmdSaveEdit.OnClick();
                    Class.clsStaticFunctions.CapNhatThanhCong(targetLayer.Name);
                }
                else
                {
                    Class.clsStaticFunctions.CanhBao("Bạn phải bật chế độ chỉnh sửa để cập nhật thông tin đối tượng!");
                    return;
                }
            }
            catch (Exception ex)
            {
                Class.clsStaticFunctions.ThongBaoLoi(ex);
            }
        }

        private void btnDong_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_mapControl != null)
                {
                    m_mapControl.CurrentTool = null;
                }

                this.Close();
            }
            catch (Exception ex)
            {
                Class.clsStaticFunctions.ThongBaoLoi(ex);
            }
        }

        private void frmCapNhatThongTinDoiTuong_Load(object sender, EventArgs e)
        {
            try
            {
                _DisabledRows = new List<int>();
            }
            catch (Exception ex)
            {
                Class.clsStaticFunctions.ThongBaoLoi(ex);
            }
        }

        private void frmCapNhatThongTinDoiTuong_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
               
                if (m_mapControl != null)
                {
                    m_mapControl.CurrentTool = null;
                }
            }
            catch (Exception ex)
            {
                Class.clsStaticFunctions.ThongBaoLoi(ex);
            }
        }

        //private void gridView_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        //{
        //    try
        //    {
        //        if (e.Column.FieldName != "colGiaTri") return;
        //        RepositoryItemLookUpEdit comboEdit;
        //        RepositoryItemDateEdit dateEdit;
        //        GridView gv = sender as GridView;
        //        string fieldValue = gv.GetRowCellValue(e.RowHandle, gv.Columns["colTruongTT"]).ToString();
        //        //string fieldName = gv.GetRowCellValue(e.RowHandle, gv.Columns["colGiaTri"]).ToString();
        //        int index = ((IFeatureLayer)m_targetLayer).FeatureClass.Fields.FindField(fieldValue);
        //        IDomain domain = ((IFeatureLayer)m_targetLayer).FeatureClass.Fields.get_Field(index).Domain;
        //        if (domain != null)
        //        {
        //            comboEdit = new RepositoryItemLookUpEdit();
        //            comboEdit.DataSource = Class.Utility.WorkingWithDomain.ConvertDomainToTable(domain); ;
        //            comboEdit.DisplayMember = "Value";
        //            comboEdit.ValueMember = "Code";
        //            comboEdit.ShowFooter = true;
        //            comboEdit.ShowHeader = false;
        //            DevExpress.XtraEditors.Controls.LookUpColumnInfo ColumnInfo =new DevExpress.XtraEditors.Controls.LookUpColumnInfo();
        //            ColumnInfo.FieldName="Value";
        //            comboEdit.Columns.Add(ColumnInfo);
        //            comboEdit.NullText = "";
        //            e.RepositoryItem = comboEdit;
        //        }
        //        if (((IFeatureLayer)m_targetLayer).FeatureClass.Fields.get_Field(index).Type == esriFieldType.esriFieldTypeDate)
        //        {
        //            dateEdit = new RepositoryItemDateEdit();
        //            dateEdit.Mask.EditMask = "dd/MM/yyyy";
        //            dateEdit.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime;
        //            dateEdit.Mask.UseMaskAsDisplayFormat = true;
        //            e.RepositoryItem = dateEdit;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Class.clsStaticFunctions.ThongBaoLoi(ex);
        //    }
        //}
    }
}